const fs = require('fs');
const PDFParser = require('pdf2json');
const docx = require('docx');
const { Document, Paragraph, TextRun, HeadingLevel, Packer } = docx;
const path = require('path');

class PDFToWordConverter {
    constructor() {
        this.pdfParser = new PDFParser();
    }

    /**
     * 将 PDF 转换为 Word 文档
     * @param {string} inputPath PDF文件路径
     * @param {string} outputPath 输出Word文件路径
     * @returns {Promise} 转换结果
     */
    async convert(inputPath, outputPath) {
        try {
            const pdfData = await this.parsePDF(inputPath);
            const docxDocument = await this.createWordDoc(pdfData);
            await this.saveWordDoc(docxDocument, outputPath);
            
            return {
                success: true,
                message: '转换成功',
                outputPath
            };
        } catch (error) {
            console.error('转换失败:', error);
            return {
                success: false,
                message: '转换失败',
                error: error.message
            };
        }
    }

    /**
     * 解析 PDF 文件
     * @param {string} inputPath PDF文件路径
     * @returns {Promise} 解析后的PDF数据
     */
    parsePDF(inputPath) {
        return new Promise((resolve, reject) => {
            this.pdfParser.on('pdfParser_dataReady', (pdfData) => {
                resolve(pdfData);
            });

            this.pdfParser.on('pdfParser_dataError', (error) => {
                reject(error);
            });

            this.pdfParser.loadPDF(inputPath);
        });
    }

    /**
     * 创建 Word 文档
     * @param {Object} pdfData PDF解析数据
     * @returns {Document} Word文档对象
     */
    createWordDoc(pdfData) {
        const sections = [];
        
        // 处理每一页
        pdfData.Pages.forEach((page, pageIndex) => {
            const paragraphs = [];
            let currentText = '';
            
            // 处理页面中的文本
            page.Texts.forEach((textItem) => {
                const decodedText = decodeURIComponent(textItem.R[0].T);
                
                // 检查是否需要创建新段落
                if (this.shouldCreateNewParagraph(textItem)) {
                    if (currentText) {
                        paragraphs.push(this.createParagraph(currentText));
                        currentText = '';
                    }
                    paragraphs.push(this.createParagraph(decodedText));
                } else {
                    currentText += decodedText + ' ';
                }
            });

            // 添加最后一个段落
            if (currentText) {
                paragraphs.push(this.createParagraph(currentText));
            }

            // 添加页面分隔符（除了最后一页）
            if (pageIndex < pdfData.Pages.length - 1) {
                paragraphs.push(new Paragraph({
                    children: [new TextRun({ break: 1 })]
                }));
            }

            sections.push({
                properties: {},
                children: paragraphs
            });
        });

        return new Document({
            sections: sections
        });
    }

    /**
     * 判断是否应该创建新段落
     * @param {Object} textItem 文本项
     * @returns {boolean}
     */
    shouldCreateNewParagraph(textItem) {
        // 根据文本特征判断是否需要新段落
        // 这里可以根据实际需求添加更多判断条件
        return textItem.y > 0 || textItem.R[0].S === 1;
    }

    /**
     * 创建段落
     * @param {string} text 段落文本
     * @returns {Paragraph}
     */
    createParagraph(text) {
        return new Paragraph({
            children: [
                new TextRun({
                    text: text.trim(),
                    size: 24 // 12pt
                })
            ]
        });
    }

    /**
     * 保存 Word 文档
     * @param {Document} doc Word文档对象
     * @param {string} outputPath 输出路径
     * @returns {Promise}
     */
    async saveWordDoc(doc, outputPath) {
        const buffer = await Packer.toBuffer(doc);
        return fs.promises.writeFile(outputPath, buffer);
    }
}

// 导出转换器类
module.exports = PDFToWordConverter;

// 使用示例
const currentDir = __dirname;
const inputPath = path.join(currentDir, 'a.pdf');
const outputPath = path.join(currentDir, 'a.docx');
const converter = new PDFToWordConverter();
converter.convert(inputPath, outputPath)
    .then(result => {
        if (result.success) {
            console.log('PDF转换Word成功！');
            console.log('输出文件路径:', result.outputPath);
        } else {
            console.error('转换失败:', result.message);
        }
    })
    .catch(error => {
        console.error('转换过程出错:', error);
    });
